package c2.cross.server.controller;

import c2.advanced.server.configuration.AdvServerEnv;
import cp.solution.pattern.Feedback;
import easy.java.spring.annotation.MyGetMapping;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@RequestMapping("/system/")
@Controller
public class SystemController extends CrossBaseController implements ApplicationContextAware {

    @Autowired
    AdvServerEnv env;

    private ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    @MyGetMapping("shutdown")
    @ResponseBody
    public Feedback shutdown(@RequestParam String secret) {
        Feedback back = new Feedback().start();
        log.warn("收到退出指令，即将退出程序");
        env.checkSecret(secret);
        new Thread(() -> {
            try {
                Thread.sleep(2000);
                SpringApplication.exit(context);
                System.exit(0);
            } catch (Exception e) {
                log.error("", e);
            }
        }).start();
        return back.text("尝试执行退出指令").stop();
    }
}
